package org.acme.client;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import java.io.IOException;

@ApplicationScoped
public class RestClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(RestClient.class.getName());

//    private static final String weather_url = "http://t.weather.sojson.com/api/weather/city/";

    private static final String wthrcdn_url = "http://wthrcdn.etouch.cn/weather_mini?city=";

    private final Client httpClient;

    private CloseableHttpClient client;

    public RestClient() {
        LOGGER.info("初始化RestClient");
        this.httpClient = ClientBuilder.newClient();
        client = HttpClientBuilder.create().build();
        LOGGER.info("初始化后的RestClient"+this.httpClient);
    }

    public String getStream(String name) {
        String result = "";
        LOGGER.info(wthrcdn_url+name);
        HttpGet httpGet = new HttpGet(wthrcdn_url+name);
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            HttpEntity httpEntity = response.getEntity();
            LOGGER.info("响应httpEntity:"+httpEntity);

            if(httpEntity != null){
                result = EntityUtils.toString(httpEntity,"UTF-8");
                LOGGER.info("天气数据："+result);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null){
                try{
                    response.close();
                }catch (Exception e){

                }
            }
        }
        return  result;
    }
}

